package com.maoyu.cloud.api.common;

import org.aspectj.lang.annotation.AfterReturning;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

@ControllerAdvice
public class GlobalResponseHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Response handleException(Exception e) {
        // 处理全局异常
        return new Response(500, e.getMessage(), null);
    }

    @ModelAttribute("response")
    public Response handleResponse() {
        // 预处理响应
        return new Response(200, "success", null);
    }

    @AfterReturning(returning = "data", pointcut = "execution(public * com.example.controller..*.*(..))")
    public void handleAfterReturning(Object data) {
        // 处理返回值
        Response response = new Response(200, "success", data);
        RequestContextHolder.getRequestAttributes().setAttribute("response", response, RequestAttributes.SCOPE_REQUEST);
    }

}